/**
 * @author mmbro
 * @homepage https://gitee.com/mmbro/
 * @date 2021年05月18日00:09:44
 * @description 注释:js日志组件
 * @link https://gitee.com/fork-code/js-log
 */
/*!
 * js-log 0.0.1
 * http://js-log.cardone.top/
 *
 *
 * Copyright 2015, 2099 cardone
 * Released under the MIT license
 * http://js-log.cardone.top/license
 *
 * Date: 2015-11-23T23:01Z
 *
 * Modifier: mmbro
 * Modified: 2021-05-18
 * Modify description: support newest browsers and es6 2021;remove all depends jquery,json2;
 * https://gitee.com/fork-code/js-log
 */
(function (factory) {
    let root = (typeof self == 'object' && self.self === self && self) || (typeof globalThis == 'object' && globalThis.global === globalThis && globalThis);

    root.jsLog = factory(root, {}, (fetch));
}(function (root, jsLog, fetch) {
    let previousJsLog = root.jsLog;

    jsLog.noConflict = function () {
        root.jsLog = previousJsLog;

        return this;
    };

    jsLog.options = {
        level: "debug",
        sendLevel: "debug",
        url: "",
        emulateJSON: false,
        data: {
            token: 'test'
        }
    };

    jsLog.config = function (options) {
        Object.assign(jsLog.options, options);
    };

    let logLevel = {
        "debug": 0,
        "info": 1,
        "warn": 2,
        "error": 4
    };

    let sendLog = function (data) {
        if (!jsLog.options.url) {
            return true;
        }
        let params = {
            method: "POST",
            mode: 'cors', // 跨域请求
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        };

        fetch(jsLog.options.url, params).then(r => console.log('sendLog result', r));

        return true;
    };
    Object.keys(logLevel).map(k => ([k, logLevel[k]])).forEach(obj => {
        (function (k, v) {
            let isName = 'is' + k.substr(0, 1).toUpperCase() + k.substr(1, k.length) + 'Enabled';

            jsLog[isName] = function () {
                return v >= logLevel[jsLog.options.level];
            };

            jsLog[k] = function (message, ex) {
                if (logLevel[jsLog.options.level] > v) {
                    return false;
                }

                if (globalThis.console) {
                    globalThis.console.log(message);
                }

                if (!jsLog.options.url) {
                    return false;
                }

                if (logLevel[jsLog.options.sendLevel] > v) {
                    return false;
                }

                let data = {
                    level: k,
                    message: message
                };

                if (message) {
                    data.message = message;
                }

                if (ex) {
                    data.ex = ex;
                }

                return sendLog(message, ex);
            };
        })(obj[0], obj[1])
    })

    return jsLog;
}));